package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.bean.OrderBean;
import com.project.bean.RiderBean;
import com.project.mapper.OrderMapper;
import com.project.mapper.RiderMapper;
import com.project.service.OrderService;
import com.project.utils.RedisGetUtil;
import com.project.vo.Infos;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderBean> implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    RiderMapper riderMapper;
    @Autowired
    RedisGetUtil redisGetUtil;


    /**
     * 计算并设置骑手的收入预览
     */
    private void countRiderIncome(OrderBean orderBean) {


    }


    @Override
    public OrderBean getOrderByCode(String code) {
        QueryWrapper qu = new QueryWrapper<>();
        qu.eq("code", code);
        OrderBean orderBean = orderMapper.selectOne(qu);
        return orderBean;
    }

    @Override
    public List<OrderBean> findAllOrder(String state, String area) {
        if (state.equals("休息中")) {
            return null;
        }
        QueryWrapper<OrderBean> qu = new QueryWrapper<>();
        qu.eq("area", area);
        //查询的可取货订单
        qu.eq("statue", "可取货");
        List<OrderBean> list = orderMapper.selectList(qu);
        List<OrderBean> list1 = new ArrayList<>();
        for (OrderBean orderBean : list) {
            if (orderBean.getArea().equals(area)) {
                list1.add(orderBean);
            }
        }
        return list1;
    }

    @Override
    public Infos updateOrderState(String riderCode, String orderCode, String statue) {
        QueryWrapper<RiderBean> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", riderCode);
        RiderBean riderBean = riderMapper.selectOne(queryWrapper);
        QueryWrapper<OrderBean> qu = new QueryWrapper<>();
        qu.eq("code", orderCode);
        OrderBean orderBean = orderMapper.selectOne(qu);

        switch (statue) {
            //进行取货转换为待取货状态
            case "unchecked":
                List<OrderBean> list = orderMapper.selectList(new QueryWrapper<OrderBean>().eq("statue", "已接单"));
                //如果超出了骑手设置的最大接收数量则无法进行接单
                if (list.size() >= riderBean.getOrderNum()) {
                    return new Infos(0, "无法进行接单，当前骑手订单已满");
                }
                //更新数据库中订单
                orderBean.setRiderId(riderBean.getRiderId());
                orderBean.setOrderStartTime(String.valueOf(LocalDateTime.now()));
                orderBean.setStatue("已接单");
                orderMapper.updateById(orderBean);
                //更新结束后对redis进行操作
                redisGetUtil.addRedisOrder(riderCode + "unchecked", orderBean);
                return new Infos(1, "修改为接单状态成功");
            //转换为正在取货状态
            case "sending":
                System.out.println("骑手取货成功");
                //更新数据库中订单
                orderBean.setStatue("送货中");
                orderMapper.updateById(orderBean);
                //更新结束后对redis进行操作
                redisGetUtil.addRedisOrder(riderCode + "sending", orderBean);
                redisGetUtil.delRedisOrder(riderCode + "unchecked", orderCode);
                return new Infos(1, "修改为配送中状态成功");
            //转化为取货结束状态
            case "ending":
                System.out.println("骑手送货成功");

                //设置结束时间
                orderBean.setEndTime(String.valueOf(LocalDateTime.now()));
                orderMapper.updateById(orderBean);
//                orderMapper.updateOrder(String.valueOf(LocalDateTime.now()), "6", "送货完毕", orderCode);
                //根据订单编号查询订单时间
                LocalDateTime starttime = LocalDateTime.parse(orderBean.getOrderStartTime().
                        substring(0, orderBean.getOrderStartTime().indexOf(".")).replace(" ", "T"));
                OrderBean o = orderMapper.selectOne(qu);
                LocalDateTime endtime = LocalDateTime.parse(o.getEndTime().
                        substring(0, o.getEndTime().indexOf(".")).replace(" ", "T"));


                Duration duration = Duration.between(starttime, endtime);
                long m = duration.toMinutes();
                //取出订单起始时间和送达时间进行对比,50分钟以上讲骑手收入设为1元
                if (m > 50) {
                    orderBean.setIncome(1);
                } else {
                    int income = 0;
                    switch (riderBean.getLevel()) {
                        case 1:
                            income = 2;
                            break;
                        case 2:
                            income = 3;
                            break;
                        case 3:
                            income = 4;
                            break;
                        case 4:
                            income = 5;
                            break;
                        case 5:
                            income = 6;
                            break;
                    }
                    orderBean.setIncome(income);
                    riderBean.setBalance(riderBean.getBalance() + income);
                    //更新数据库中订单
                    orderBean.setStatue("送货完毕");
                }
                orderMapper.update(orderBean, new QueryWrapper<OrderBean>().eq("code", orderCode));
                riderMapper.updateById(riderBean);
                //更新结束后对redis进行操作
                Infos info = redisGetUtil.delRedisOrder(riderCode + "sending", orderCode);
                if (info.getCode() == 0) {
                    return new Infos(0, "修改redis状态失败");
                }
                return new Infos(1, "修改送货完毕状态成功");

        }
        return new Infos(0, "修改状态失败");
    }

    @Override
    public List<OrderBean> findAllOrderByStatue(String riderCode, String statue) {
//        QueryWrapper<OrderBean> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("statue", statue);
//        RiderBean r = riderMapper.selectOne(new QueryWrapper<RiderBean>().eq("code", riderCode));
//        queryWrapper.eq("fk_riderId", r.getRiderId());
//        List<OrderBean> list = orderMapper.selectList(queryWrapper);
        String st = "";
        if (statue.equals("送货中")) {
            st = "sending";
        } else if (statue.equals("已接单")) {
            st = "unchecked";
        }
        List<OrderBean> list = redisGetUtil.getOrderList(riderCode + st);
        if (list == null) {
            return null;
        }

//        //循环计算当前骑手每单可支配的收入
        for (OrderBean orderBean : list) {
            //通过骑手外键id获取骑手对象以及其级别
            int riderId = orderBean.getRiderId();
            RiderBean riderBean = riderMapper.selectById(riderId);
            //根据骑手级别进行对订单的收入进行计算
            int income = 0;
            switch (riderBean.getLevel()) {
                case 1:
                    income = 2;
                    break;
                case 2:
                    income = 3;
                    break;
                case 3:
                    income = 4;
                    break;
                case 4:
                    income = 5;
                    break;
                case 5:
                    income = 6;
                    break;
            }
            //设置骑手收入
            orderBean.setIncome(income);
//            orderMapper.updateById(orderBean);
        }
        return list;
    }

    @Override
    public List<OrderBean> findAllOrderByRiderCodeAndDateAndStatue(String riderCode, String date) {
        QueryWrapper<RiderBean> qw = new QueryWrapper();
        RiderBean ri = riderMapper.selectOne(qw.eq("code", riderCode));
        QueryWrapper<OrderBean> qw2 = new QueryWrapper();
        qw2.eq("fk_riderId", ri.getRiderId());

        qw2.eq("statue", "送货完毕");
        //查询出订单对象
        List<OrderBean> list = orderMapper.selectList(qw2);
        List<OrderBean> list2 = new ArrayList<>();

        for (OrderBean orderBean : list) {
            String daytime = orderBean.getEndTime().substring(0, orderBean.getEndTime().indexOf("."));
            String x = daytime.replace(" ", "T");
            String day = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDateTime.parse(x));

            if (day.equals(LocalDate.now() + "")) {
                list2.add(orderBean);
            }
        }
        return list2;
    }

    @Override
    public List<OrderBean> findOrderByRiderCodeAndStatus(String riderCode) {
        return orderMapper.findOrder(riderCode);
    }
}
